package com.whfc.fse.queue;

import com.alibaba.fastjson.JSON;
import com.whfc.common.constant.QueueConst;
import com.whfc.common.enums.NetState;
import com.whfc.common.util.DateUtil;
import com.whfc.fse.dao.FseLiftDataMapper;
import com.whfc.fse.dao.FseLiftMapper;
import com.whfc.fse.dao.FseSyncDao;
import com.whfc.fse.dto.FseLiftDataDTO;
import com.whfc.fse.dto.FseWarnDTO;
import com.whfc.fse.entity.FseDeviceLiftDataLog;
import com.whfc.fse.entity.FseLift;
import com.whfc.fse.entity.FseLiftData;
import com.whfc.fse.entity.FseSync;
import com.whfc.fse.enums.FseLiftSide;
import com.whfc.fse.enums.FseType;
import com.whfc.fse.enums.FseWarnRuleType;
import com.whfc.fse.manager.FseWarnMgr;
import com.whfc.fse.pushPlatform.ShengSiFseApi;
import com.whfc.fse.pushPlatform.ShiShouFseApi;
import com.whfc.fse.pushPlatform.model.ShiShouCraneWarnDTO;
import com.whfc.fse.pushPlatform.model.ShiShouLiftRealDTO;
import com.whfc.influx.dao.FseLiftDataLogDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 处理硬件上传的升降机实时数据
 *
 * @author sun_guodong
 * @date 2020-05-26
 */
@Component
@RabbitListener(queuesToDeclare = {@Queue(name = QueueConst.FSE_LIFT_REAL_DATA)}, concurrency = "1-2",containerFactory = "baseFactory")
public class FseLiftRealDataQueueListener {

    private static final Logger logger = LoggerFactory.getLogger(FseLiftRealDataQueueListener.class);

    @Autowired
    private FseLiftMapper fseLiftMapper;

    @Autowired
    private FseLiftDataMapper fseLiftDataMapper;

    @Autowired
    private FseLiftDataLogDao fseLiftDataLogDao;

    @Autowired
    private FseWarnMgr fseWarnMgr;

    @Autowired
    private ShiShouFseApi shiShouFseApi;

    @Autowired
    private FseSyncDao fseSyncDao;

    @Autowired
    private ShengSiFseApi shengSiFseApi;

    @RabbitHandler
    public void handle(String msg) {
        try {
            logger.info("消息消费者处理升降机实时数据,msg:{}", msg);
            FseLiftDataDTO fseLiftDataDTO = JSON.parseObject(msg, FseLiftDataDTO.class);
            String sn = fseLiftDataDTO.getSn();
            String platform = fseLiftDataDTO.getPlatform();
            FseLift fseLift = fseLiftMapper.selectByPlatformAndSn(platform, sn);
            if (fseLift == null) {
                logger.warn("该升降机不存在,platform:{},sn:{}", platform, sn);
                return;
            }
            int liftSide = FseLiftSide.LEFT.getValue();
            if (sn.equals(fseLift.getRightSn())) {
                liftSide = FseLiftSide.RIGHT.getValue();
            }
            fseLiftDataDTO.setLiftSide(liftSide);
            Integer liftId = fseLift.getId();
            // 更新升降机数据
            FseLiftData fseLiftData = new FseLiftData();
            BeanUtils.copyProperties(fseLiftDataDTO, fseLiftData);
            fseLiftData.setLiftId(liftId);
            fseLiftDataMapper.updateByLiftIdAndLiftSide(fseLiftData);

            // 插入历史数据
            FseDeviceLiftDataLog deviceLiftDataLog = new FseDeviceLiftDataLog();
            BeanUtils.copyProperties(fseLiftDataDTO, deviceLiftDataLog);
            deviceLiftDataLog.setLiftId(liftId);
            deviceLiftDataLog.setLiftSide(liftSide);
            fseLiftDataLogDao.insert(deviceLiftDataLog);

            // 获取同步配置
            Integer deptId = fseLift.getDeptId();
            List<Integer> platforms = new ArrayList();
            platforms.add(2);
            platforms.add(4);
            List<FseSync> list = fseSyncDao.seiectByDeptIdAndPlatforms(deptId,platforms);
            if (list.size() > 0) {
                for (FseSync fseSync : list) {
                    switch (fseSync.getPlatform()) {
                        // 石首升降机平台推送
                        case 2:
                            ShiShouLiftRealDTO shiShouLiftRealDTO = new ShiShouLiftRealDTO();
                            shiShouLiftRealDTO.setRecDate(DateUtil.formatDate(fseLiftDataDTO.getTime(), "yyyy-MM-dd HH:mm:ss"));
                            shiShouLiftRealDTO.setDeviceId(sn);
                            shiShouLiftRealDTO.setCreanceId(sn);
                            shiShouLiftRealDTO.setDeviceName(fseLift.getCode());
                            shiShouLiftRealDTO.setLiftLoad((int)Math.round(fseLiftDataDTO.getWeight()*1000));
                            shiShouLiftRealDTO.setFloor(fseLiftDataDTO.getFloor());
                            shiShouLiftRealDTO.setHeight(fseLiftDataDTO.getHeight());
                            shiShouLiftRealDTO.setSpeed(fseLiftDataDTO.getSpeed());
                            shiShouLiftRealDTO.setAngle(fseLiftDataDTO.getDipAngle());
                            shiShouLiftRealDTO.setWindSpeed(fseLiftDataDTO.getWindSpeed());
                            shiShouLiftRealDTO.setPeopleNum(fseLiftDataDTO.getPersonNo());
                            shiShouLiftRealDTO.setDriverId("吴军");
                            shiShouFseApi.reportRealLift(shiShouLiftRealDTO, fseSync);
                            break;
                        // 升思升降机平台推送
                        case 4:
                            shengSiFseApi.pushLiftRealData(fseLiftDataDTO);
                            break;
                    }
                }
            }

            //更新在线信息
            Date time = fseLiftDataDTO.getTime();
            int netState = NetState.OFFLINE.getValue();
            if (DateUtil.isToday(time)) {
                netState = NetState.ONLINE.getValue();
            }
            if (FseLiftSide.RIGHT.getValue().equals(liftSide)) {
                fseLift.setRightNetState(netState);
            } else {
                fseLift.setLeftNetState(netState);
            }
            fseLiftMapper.updateByPrimaryKeySelective(fseLift);

            if (fseLiftDataDTO.getLiftStatus() == null) {
                return;
            }
            // 处理报警数据
            FseWarnRuleType fseWarnRuleType = FseWarnRuleType.parseByValue(fseLiftDataDTO.getLiftStatus());
            if (fseWarnRuleType != null) {
                String triggerValue = this.getTriggerValue(fseWarnRuleType, fseLiftDataDTO);
                FseWarnDTO fseWarnDTO = new FseWarnDTO();
                fseWarnDTO.setDeptId(fseLift.getDeptId());
                fseWarnDTO.setCode(fseLift.getCode());
                fseWarnDTO.setFseType(FseType.LIFT);
                fseWarnDTO.setFseWarnRuleType(fseWarnRuleType);
                fseWarnDTO.setTriggerTime(time);
                fseWarnDTO.setTriggerObjectId(fseLift.getId());
                fseWarnDTO.setTriggerValue(triggerValue);
                fseWarnMgr.handleFseWarn(fseWarnDTO);

                if (list.size() > 0) {
                    for (FseSync fseSync : list) {
                        switch (fseSync.getPlatform()) {
                            // 石首平台推送报警
                            case 1:
                                ShiShouCraneWarnDTO shiShouCraneWarnDTO = new ShiShouCraneWarnDTO();
                                shiShouCraneWarnDTO.setTime(DateUtil.formatDate(time, "yyyy-MM-dd HH:mm:ss"));
                                shiShouCraneWarnDTO.setCraneNum(sn);
                                shiShouCraneWarnDTO.setInformation(triggerValue);
                                shiShouFseApi.reportLiftViolation(shiShouCraneWarnDTO,fseSync);
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error("消息消费者处理升降机实时数据失败", e);
        }

    }

    /**
     * 获取触发值
     *
     * @param ruleType
     * @param fseLiftDataDTO
     * @return
     */
    private String getTriggerValue(FseWarnRuleType ruleType, FseLiftDataDTO fseLiftDataDTO) {
        String triggerValue = "";
        switch (ruleType) {
            case LIFT_HIGT:
                triggerValue = String.valueOf(fseLiftDataDTO.getHeight());
                break;
            case LIFT_WEIGH:
                triggerValue = String.valueOf(fseLiftDataDTO.getWeight());
                break;
            case LIFT_SPEED:
                triggerValue = String.valueOf(fseLiftDataDTO.getSpeed());
                break;
            case LIFT_FRONT_GATE:
                triggerValue = String.valueOf(fseLiftDataDTO.getFrontDoorState());
                break;
            case LIFT_BACK_GATE:
                triggerValue = String.valueOf(fseLiftDataDTO.getBackDoorState());
                break;
            case LIFT_WIND_SPEED:
                triggerValue = String.valueOf(fseLiftDataDTO.getWindSpeed());
                break;
            case LIFT_TURN:
                triggerValue = String.valueOf(fseLiftDataDTO.getDipAngle());
                break;
            case LIFT_PERSON:
                triggerValue = String.valueOf(fseLiftDataDTO.getPersonNo());
                break;
            default:
                triggerValue = "";
                break;
        }
        return triggerValue;

    }

}
